public class RWLock
{
	private int readersReading ;
	private int writersWaiting ;
	private boolean writing;
	public synchronized void startWriting ()
	{
		writersWaiting ++; // writers can request writing at any time ( synchronized )
		try
		{
			// wait until no one is reading / writing
			while ( writing || readersReading > 0) wait ();
		} catch ( InterruptedException E ) {
			notifyAll (); // if interrupted others shall get a chance
		} finally { writersWaiting --; }
		// finally it ’s out turn
		writing = true ;
	}
	public synchronized void endWriting ()
	{
		writing = false ;
		notifyAll (); // wake up others waiting to read / write
	}
	public synchronized void startReading ()
	{
		// wait until no one is writing or willing to write
		// -> priority to writers

		try
		{
			while ( writing || writersWaiting > 0) wait ();
		} catch ( InterruptedException E ) {}
		readersReading ++;
	}
	public synchronized void endReading ()
	{
		readersReading --;
		notifyAll (); // wake up others waiting to read / write
	}
}
